﻿using HAF.Dispatcher.WorkItem;
using HAF.LogUtility.Assistantor;
using Iptv.MediaReporter.Helper;
using Iptv.MediaReporter.Model;
using RDS.Core;
using System;
using System.IO;
using System.Threading;

namespace Iptv.MediaReporter.SubItems
{
    /// <summary>
    /// 指纹结果查询任务
    /// </summary>
    public class WatchFingerPrintItem : BaseWorkerItem, IDisposable
    {
        private LoadConfig _runSiteConfig;
        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            WriteDebugMessage("指纹结果查询任务结束");
        }
        /// <summary>
        /// 
        /// </summary>
        public override void ExecItem()
        {
            base.ExecItem();
            RefreshConfig();
            WatchResult();
        }

        private void RefreshConfig()
        {
            //获取本地配置文件 每次执行的时候读取，实现热配置
            string loadConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, RuntimeAdapter.PluginDir, "ReportConfig.json");
            ShowDebugMessage("获取本地配置文件{0}", loadConfigPath);
            _runSiteConfig = JsonAssistant.FromFile<LoadConfig>(loadConfigPath);
        }

        private void WatchResult()
        {
            FingerPrintWatch printWatch = new FingerPrintWatch()
            {
                jobId = WorkJson
            };

            try
            {
                string postData = JsonAssistant.Serialize(printWatch);
                ShowDebugMessage(postData);
                string responseStr = WebHelper.GetHttpResponse(_runSiteConfig.FingerPrintQueryApiUrl, "Post", "application/json", postData);
                if (!string.IsNullOrEmpty(responseStr))
                {
                    ShowDebugMessage(responseStr);
                    /**
                     * {"code":0,"message":"SUCCESS",
                     * "data":{"jobId":"d081bdb5a1d74d578876184bf2a818ac","reportRes":10,"estimateTime":null,"completePercent":null,
                     * "vlist":[{"guid":"20000002000000000100000008921829","subJobId":"cffcc8885c1946db90d7f3ea768ae7e4",
                     * "videoUrl":"/opt/vdnagen/video/unicom/202412/25/f76dc16aa4fbc000_OTT_HD_1920X1080_4000_VBR.mp4",
                     * "fingerUrl":"null","hashCode":null,"status":1,"message":null}]}}
                     **/
                    var fpResult = JsonAssistant.Deserialize<FingerPrintResult>(responseStr);
                    if (fpResult != null)
                    {
                        WorkOutMessage outTaskMessage = new WorkOutMessage();
                        outTaskMessage.ID = WorkID;
                        outTaskMessage.CmdUrl = printWatch.jobId;

                        ShowDebugMessage(fpResult.data.vlist[0].status.ToString());
                        //status 1 任务启动 2 执行中 3 执行成功 4 执行失败 5 超时 6 取消
                        if (fpResult.data.vlist[0].status == 3)
                        {
                            outTaskMessage.Token = fpResult.data.vlist[0].hashCode;
                            CallBack?.Invoke(null, outTaskMessage);
                            //暂停10秒
                            Thread.Sleep(10 * 1000);
                            EndProcess?.Invoke(WorkID, true);
                        }
                        else if (fpResult.data.vlist[0].status == 4)
                        {
                            EndProcess?.Invoke(WorkID, false);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                EndProcess(WorkID, false);
                ShowErrMessage(ex.ToString());
            }
            
        }
    }
}
